package ru.reaperoq.inventory.screens.main.tabs

import UserViewModel
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.NavController
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import androidx.navigation.navigation
import models.shared.UserUi
import models.user.UserEvent
import org.koin.androidx.compose.navigation.koinNavViewModel
import ru.reaperoq.inventory.navigation.Screens
import ru.reaperoq.inventory.screens.main.MyLocationScreen
import ru.reaperoq.inventory.screens.main.admin.locations.LocationsScreen
import ru.reaperoq.inventory.screens.main.admin.objects.AdminObjectsScreen
import ru.reaperoq.inventory.screens.main.admin.objects.EditObjectsScreen
import ru.reaperoq.inventory.screens.main.admin.users.UsersScreen
import ru.reaperoq.inventory.screens.main.profile.ProfileScreen

@Composable
fun TabsScreen(
    modifier: Modifier = Modifier,
    viewModel: UserViewModel = koinNavViewModel(key = "USER_VIEW_MODEL", viewModelStoreOwner = (LocalContext.current as ComponentActivity)),
    onLogout: () -> Unit,
    onOpenInventoryScanner: () -> Unit,
    onOpenEditScanner: (String) -> Unit
) {
    val navController = rememberNavController()
    val viewState by viewModel.viewStates().collectAsState()

    LaunchedEffect(Unit) {
        viewModel.obtainEvent(UserEvent.LoadUser)
    }
    if (viewState.user == null) {
        Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
            CircularProgressIndicator()
        }
    } else {
        Scaffold(
            modifier = modifier
                .statusBarsPadding(),
            bottomBar = {
                MyBottomNavigationBar(viewState.user!!.role, navController)
            }
        ) { padding ->
            NavHost(
                modifier = modifier
                    .consumeWindowInsets(padding)
                    .padding(padding),
                navController = navController,
                startDestination = Screens.MyInventory.route,
            ) {
                composable(Screens.MyInventory.route) {
                    MyLocationScreen(onOpenScanner = onOpenInventoryScanner)
                }
                composable(Screens.Profile.route) {
                    ProfileScreen(
                        user = viewState.user!!,
                        onLogout = {
                            viewModel.obtainEvent(UserEvent.Logout)
                            onLogout()
                        }
                    )
                }
                composable(Screens.AllLocations.route) {
                    LocationsScreen()
                }
                navigation(
                    route = Screens.AllInventories.route,
                    startDestination = Screens.AllInventoriesList.route
                ) {
                    composable(Screens.AllInventoriesList.route) {
                        AdminObjectsScreen(
                            modifier = Modifier.fillMaxSize(),
                            onOpenEdit = { id, key ->
                                navController.navigate(
                                    "${Screens.AllInventoriesEdit.route}/$key/${id ?: "id"}"
                                )
                            }
                        )
                    }
                    composable("${Screens.AllInventoriesEdit.route}/{key}/{id}", arguments = listOf(
                        navArgument("key") { type = NavType.StringType },
                        navArgument("id") { type = NavType.StringType }
                    )) { navBackStackEntry ->
                        val context = LocalContext.current
                        navBackStackEntry.arguments?.getString("key")?.let {
                            Log.d(
                                "AllInventoriesEdit",
                                "key: $it, id: ${navBackStackEntry.arguments?.getString("id")}"
                            )
                            EditObjectsScreen(
                                userRole = viewState.user!!.role,
                                onOpenScanner = onOpenEditScanner,
                                key = it,
                                id = navBackStackEntry.arguments?.getString("id")?.toIntOrNull(),
                                viewModel = koinNavViewModel(
                                    key = it,
                                    viewModelStoreOwner = (context as ComponentActivity)
                                )
                            ) {
                                navController.navigateUp()
                            }
                        }
                    }
                }
                composable(Screens.AllProfiles.route) {
                    UsersScreen()
                }
            }
        }
    }
}

@Composable
fun MyBottomNavigationBar(role: UserUi.Role, navController: NavController) {
    val screens = mutableListOf(
        Screens.MyInventory,
        Screens.Profile
    )
    if (role == UserUi.Role.MODERATOR || role == UserUi.Role.ADMIN) {
        screens.add(1, Screens.AllInventories)
    }
    if (role == UserUi.Role.ADMIN) {
        screens.add(2, Screens.AllLocations)
        screens.add(screens.lastIndex, Screens.AllProfiles)
    }

    BottomAppBar {
        screens.forEach { screen ->
            val navBackStackEntry by navController.currentBackStackEntryAsState()
            val currentRoute = navBackStackEntry?.destination
            val selected = currentRoute?.hierarchy?.any { it.route == screen.route } == true
            NavigationBarItem(
                selected = selected,
                onClick = {
                    navController.navigate(screen.route) {
                        popUpTo(navController.graph.findStartDestination().id) {
                            saveState = true
                        }
                        launchSingleTop = true
                        restoreState = true
                    }
                },
                label = {
                    Text(text = screen.label!!)
                },
                icon = {
                    val icon = (if (selected) screen.iconSelected else screen.iconDefault)!!
                    Icon(imageVector = icon, contentDescription = screen.label)
                }
            )
        }
    }
}